package com.zzyy.study.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2024-04-15 22:15
 */
@RestController
public class SemaphoreController
{
    private static final Integer NUMBER = 20;

    private Semaphore semaphore = new Semaphore(NUMBER);

    @GetMapping(value = "/semaphore1")
    public String helloSemaphore() throws InterruptedException
    {
        String retValue;

        boolean acquireBoolean = semaphore.tryAcquire(1, 1, TimeUnit.SECONDS);
        if(acquireBoolean)
        {
            try
            {
                retValue = Thread.currentThread().getName()+"\t"+"访问成功";
                try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
            } finally {
                semaphore.release();
            }
        }else{
            //retValue = Thread.currentThread().getName()+"\t"+"访问失败令牌用完，/(ㄒoㄒ)/~~";
            retValue = "0000";
        }
        System.out.println("retValue: "+retValue);
        return retValue;
    }

}
